package com.example.szh.fragment;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.szh.R;
import com.example.szh.adapter.NewsVpAdapter;
import com.example.szh.adapter.TextBannerAdapter;
import com.example.szh.db.DBManager;
import com.example.szh.entity.BaseEntity;
import com.example.szh.entity.ChannelEntity;
import com.example.szh.entity.TextBannerEntity;
import com.example.szh.entity.UserEntity;
import com.example.szh.http.HttpCode;
import com.example.szh.mvp.contract.LREContract;
import com.example.szh.mvp.di.DaggerLREConponent;
import com.example.szh.mvp.di.LREMoudes;
import com.example.szh.mvp.presenter.LREPresenter;
import com.example.szh.mvp.view.news.ChannelActivity;
import com.example.szh.mvp.view.news.ContentNewsFragment;
import com.example.szh.nextwork.view.BaseFragment;
import com.flyco.tablayout.SlidingTabLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.transformer.ZoomOutPageTransformer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class NewsFragment extends BaseFragment<LREPresenter> implements LREContract.ILREView ,
        OnBannerListener<TextBannerEntity.Values> , OnRefreshLoadMoreListener {
    private SlidingTabLayout tabLayout;
    private ViewPager viewPager;
    private Banner<TextBannerEntity.Values, TextBannerAdapter> news_text_banner;
    private TextBannerAdapter textBannerAdapter;
    private NewsVpAdapter newsVpAdapter;
    private List<Fragment> fragments;
    private ImageView news_more_img;
    private MyService myService;

    @Override
    public void refreshAll(BaseEntity entity) {
        if (entity instanceof TextBannerEntity){
            //文字banner返回
            TextBannerEntity textBannerEntity = (TextBannerEntity) entity;
            if (textBannerEntity.getValues() == null) {
                ToastUtils.showShort("文字广告数据丢失");
                return;
            }
            textBannerAdapter = new TextBannerAdapter(textBannerEntity.getValues());
            textBannerAdapter.setOnBannerListener(this);
            news_text_banner.setAdapter(textBannerAdapter)
                    .setOrientation(Banner.VERTICAL)
                    .setPageTransformer(new ZoomOutPageTransformer())
                    .setOnBannerListener(this);
        }else if (entity instanceof ChannelEntity){
            //频道列表数据
            //按照频道数量以及频道id初始化fragments
            ChannelEntity channelEntity = (ChannelEntity) entity;
            LogUtils.json(channelEntity);
            if (channelEntity.getValues()==null){
                ToastUtils.showShort("无频道数据");
                return;
            }
            for (int i = 0;i < channelEntity.getValues().size();i ++){
                fragments.add(new ContentNewsFragment(channelEntity.getValues().get(i).channel_id));
            }
            newsVpAdapter = new NewsVpAdapter(getFragmentManager(), channelEntity.getValues(), fragments);
            viewPager.setAdapter(newsVpAdapter);
            tabLayout.setViewPager(viewPager);
        }
    }

    @Override
    public void refreshRecyckerView(BaseEntity entity) {

    }

    @Override
    public void loadMoreRecyclerView(BaseEntity entity) {



    }

    @Override
    public int bindLayout() {
        return R.layout.fragment_news;
    }

    @Override
    public void initView() {
        tabLayout = f(R.id.news_tab);
        viewPager = f(R.id.news_vp);
        news_more_img = f(R.id.news_more_img);
        news_text_banner = f(R.id.news_text_banner);
        news_more_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ChannelActivity.class);
                startActivity(intent);
            }
        });
        myService = new MyService();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("succes");
        getActivity().registerReceiver(myService,intentFilter);
    }

    public class MyService extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("succes")){
                initData();
            }
        }
    }

    @Override
    public void inject() {
        DaggerLREConponent.builder().lREMoudes(new LREMoudes(this)).build().injectNewsFragment(this);
    }

    @Override
    public void initData() {
        fragments = new ArrayList<>();
        //获取顶部文字banner数据源
        List<UserEntity> users = null;
        try {
            users = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class).list();
        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean flag = users.size() == 0;
        //获取频道数据源
        Map<String, Object> bannerMap = new HashMap<>();
        bannerMap.put("code", HttpCode.TEXTBANNERCODE);
        Map<String, Object> channelMap = new HashMap<>();
        channelMap.put("code", HttpCode.USERCHANNELCODE);
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        UserEntity userEntity = null;
        try {
            userEntity = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (userEntity!=null){
            channelMap.put("imie", PhoneUtils.getIMEI());
            channelMap.put("userId",userEntity.getUser_id());
            p.requestAll(bannerMap,channelMap);
        }



    }
    @Override
    public void onStart() {
        super.onStart();
        news_text_banner.start();
    }

    @Override
    public void onStop() {
        super.onStop();
        news_text_banner.stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        news_text_banner.destroy();
    }

    @Override
    public void OnBannerClick(TextBannerEntity.Values data, int position) {
//        com.example.szh.utils.ToastUtils.showMsg("aaa");
//        TextBannerEntity.Values values = textBannerAdapter.getData(position);
//        String url = values.news_url;
//        long id =values.news_id;
//        Bundle bundle = new Bundle();
//        bundle.putLong("news_id",id);
//        bundle.putString("news_url",url);
//        startPage(bundle, NewsValuesActivity.class);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {


        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        try {
            UserEntity userEntity = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);
            if (userEntity!=null){
                Map<String, Object> channelMap = new HashMap<>();
                channelMap.put("code", HttpCode.USERCHANNELCODE);
                channelMap.put("imie", PhoneUtils.getIMEI());
                channelMap.put("userId",userEntity.getUser_id());
                p.requestLoad(channelMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        refreshLayout.finishLoadMore();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        try {
            UserEntity userEntity = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);
            if (userEntity!=null){
                Map<String, Object> channelMap = new HashMap<>();
                channelMap.put("code", HttpCode.USERCHANNELCODE);
                channelMap.put("imie", PhoneUtils.getIMEI());
                channelMap.put("userId",userEntity.getUser_id());
                p.requestRefresh(channelMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        refreshLayout.finishRefresh();
    }
}